package cn.icare.cms.impl;

import cn.icare.cms.ItemStoreService;
import cn.icare.cms.dao.mapper.CustomMapper;
import cn.icare.cms.dao.mapper.ItemStoreMapper;
import cn.icare.cms.dao.mapper.StoreMapper;
import cn.icare.cms.dao.po.ItemStore;
import cn.icare.cms.dao.po.Store;
import cn.icare.cms.model.ro.AddItemStoreRO;
import cn.icare.cms.model.ro.EditItemStoreRO;
import cn.icare.cms.model.ro.SaveItemStoreRO;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class ItemStoreServiceImpl implements ItemStoreService {


    @Resource
    private ItemStoreMapper itemStoreMapper;

    @Resource
    private StoreMapper storeMapper;

    @Resource
    private CustomMapper customMapper;//自定义通用mapper

    private final Logger logger = LoggerFactory.getLogger(ItemStoreServiceImpl.class);


    @Override
    public Long createOne(AddItemStoreRO ro, String userName) {
        this.logger.warn(String.format("管理员:%s,修改了商品库存，参数为:%s", userName
                , JSON.toJSONString(ro)));
        try {

            Integer storeId = ro.getStoreid();

            boolean isAdd = false;
            ItemStore model = this.getModel(ro.getItemid(), storeId);
            if (model == null) {
                isAdd = true;
                model = new ItemStore();
                model.setItemid(ro.getItemid());
                model.setStoreid(ro.getStoreid());
                model.setAreaid(ro.getAreaid());//仓库所在区域id
            }
            model.setNum(ro.getNum());

            int result = 0;
            if (isAdd) {
                this.itemStoreMapper.insertSelective(model);
            } else {
                this.itemStoreMapper.updateByPrimaryKeySelective(model);

            }
            if (result > 0) {
                return model.getId();
            }

        } catch (Exception ex) {
            this.logger.error("createOne异常", ex);
        }
        return 0L;
    }

    @Override
    public boolean updateOne(EditItemStoreRO ro) {
        try {
            ItemStore model = new ItemStore();
            model.setNum(ro.getNum());

            Example example = new Example(ItemStore.class);
            Example.Criteria criteria = example.createCriteria();

            criteria.andEqualTo("itemid", ro.getItemid());
            criteria.andEqualTo("storeid", ro.getStoreid());
            int result = this.itemStoreMapper.updateByExampleSelective(model, example);
            if (result > 0) {
                return true;
            }
        } catch (Exception ex) {
            this.logger.error("updateOne", ex);
        }
        return false;
    }

    @Override
    public boolean deleteOne(Long itemId, Integer storeId) {
        Example example = new Example(ItemStore.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("itemid", itemId);
        criteria.andEqualTo("storeid", storeId);
        int result = this.itemStoreMapper.deleteByExample(example);
        return result > 0;
    }

    @Override
    public MsgDatasVO getList(Long itemId, Integer pageNum, Integer pageSize) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            if (pageSize == 0) {
                Example example = new Example(ItemStore.class);
                Example.Criteria criteria = example.createCriteria();
                if (itemId != null && itemId > 0) {
                    criteria.andEqualTo("itemid", itemId);
                }

                List<ItemStore> dataList = this.itemStoreMapper.selectByExample(example);
                result.setTotal(dataList.size());
                result.setDatas(dataList);
            } else {
                PageHelper.startPage(pageNum, pageSize);
                Example example = new Example(ItemStore.class);
                Example.Criteria criteria = example.createCriteria();
                if (itemId != null && itemId > 0) {
                    criteria.andEqualTo("itemid", itemId);
                }
                List<ItemStore> dataList = this.itemStoreMapper.selectByExample(example);
                PageInfo pageInfo = new PageInfo(dataList);
                result.setTotal(pageInfo.getTotal());
                result.setDatas(dataList);
            }
        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public MsgDatasVO getListByItem(Long itemId) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            String sql = "select a.id,a.name,a.areaid,b.num from t_store a JOIN t_item_store b ON\n" +
                    "a.id=b.storeid and  b.itemid=" + itemId;
            List<Map<String, Object>> dataList = customMapper.select(sql);
            result.setDatas(dataList);
            result.setTotal(dataList.size());
        } catch (Exception e) {
            this.logger.error("getListByItem 异常", e);
        }
        return result;
    }

    @Override
    public MsgDatasVO getWaitEditNum(Long itemId, Integer areaId) {
        MsgDatasVO result = new MsgDatasVO();
        try {
            String sql = "select a.id,a.name,a.areaid,IFNULL(b.num,0) num from t_store a LEFT JOIN t_item_store b ON\n" +
                    "a.id=b.storeid and  b.itemid=" + itemId;
            if (areaId != null && areaId > 0) {
                sql += " where a.areaid=" + areaId;
            }
            sql += " order by num desc";
            List<Map<String, Object>> dataList = customMapper.select(sql);
            result.setDatas(dataList);
            result.setTotal(dataList.size());
        } catch (Exception e) {
            this.logger.error("getListByItem 异常", e);
        }
        return result;

    }

    @Override
    public List<Map<String, Object>> getItemStoreList(Long itemId, Long areaId, Integer minNum) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select a.storeid,b.lat,b.lon from t_item_store a,t_store b where a.storeid=b.id\n" +
                "and a.itemid=" + itemId + " and a.areaid=" + areaId + " and a.num>=" + minNum);
        return this.customMapper.select(stringBuffer.toString());
    }

    @Override
    public boolean subtractItemNum(Long itemId, Integer storeId, Integer num) {
        String sql=String.format("update t_item_store set num=num-%s where itemid=%s and storeid=%s and num>=%s",
                num,itemId,storeId,num);
        return this.customMapper.update(sql)>0;
    }

    @Override
    public boolean addItemNum(Long itemId, Integer storeId, Integer num) {
        String sql=String.format("update t_item_store set num=num+%s where itemid=%s and storeid=%s",
                num,itemId,storeId);
        return this.customMapper.update(sql)>0;
    }

    private ItemStore getModel(Long itemId, Integer storeId) {
        Example example = new Example(ItemStore.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("itemid", itemId);
        criteria.andEqualTo("storeid", storeId);
        return this.itemStoreMapper.selectOneByExample(example);
    }
}
